package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;

public class BibliotecaApp {

    private PrintStream printStream;
    private LibraryManager manager;

    public BibliotecaApp(PrintStream printStream, LibraryManager manager) {
        this.printStream = printStream;
        this.manager = manager;
    }

    public static void main(String[] args) {
        ArrayList<Book> bookList = populateBooksList();
        LibraryManager manager = new LibraryManager(bookList);

        new BibliotecaApp(System.out, manager).runApp();
    }

    private static ArrayList<Book> populateBooksList() {
        ArrayList<Book> tempBookList = new ArrayList<Book>();
        tempBookList.add(new Book("Gulliver's Travels"));
        tempBookList.add(new Book("The Hobbit"));
        tempBookList.add(new Book("Call of the Wild"));

        return tempBookList;
    }

    private void runApp() {
        welcomeMessage();
        listAvailableBooks();
        displayListOptions();
        handleUserListChoice(new BufferedReader(new InputStreamReader(System.in)), new UserInputCondition());
    }

    public void welcomeMessage() {
        printStream.println("Welcome to Biblioteca!");
        printStream.println();
    }

    public void listAvailableBooks() {
        manager.printBooks(printStream);
    }

    public void displayListOptions() {
        printStream.println("Enter Number for Option.");
        printStream.println("Enter 1 to list books");
    }


    public void handleUserListChoice(BufferedReader reader, UserInputCondition condition) {
        String input;

        while (condition.isTrue()) {
            input = getUserInput(reader);
            processUserInput(input, reader);
        }
    }

    private String getUserInput(BufferedReader reader) {
        String input = "0";

        try {
            input = reader.readLine();
        } catch (IOException ex) {
            printStream.println("Error!");
            ex.printStackTrace();
        }
        return input;
    }

    private void processUserInput(String input, BufferedReader reader) {

        if(input.equals("1")){
            listAvailableBooks();
        } else if (input.equals("2")) {
            manager.checkOutBook(getTitleFromUser(reader));
        } else {
            printStream.println("Select a valid option!");
        }
    }

    private String getTitleFromUser(BufferedReader reader) {
        printStream.println("Enter a title:");
        return getUserInput(reader);
    }
}